package com.show.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.show.config.DemoDataListener;
import com.show.pojo.Trainee;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;

/**
 * @author 绛河
 */
@WebServlet("/upload")
@MultipartConfig
public class UploadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("OK");
        //设置请求的编码格式
        req.setCharacterEncoding("UTF-8");
        //获取普通表单项（获取参数）

        Part part = req.getPart("myfile");
        System.out.println(part);
        //通过Part对象得到上传的文件名
        String fileName = part.getSubmittedFileName();
        System.out.println("上传文件名：" + fileName);
        //得到文件存放的路径
        String filePath = req.getServletContext().getRealPath("/xlsx");
        File uploadFile = new File(filePath);
        // 如果此文件夹不存在就直接创建一个
        if (!uploadFile.exists()) {
            uploadFile.mkdir();
        }
        System.out.println("文件存放路径：" + filePath);
        //上传文件到指定目录
        part.write(filePath + "/" + fileName);
        String fi = filePath+"\\"+fileName;
        ExcelReader excelReader = EasyExcel.read(fi, Trainee.class, new DemoDataListener()).build();
        ReadSheet readSheet = EasyExcel.readSheet(0).build();
        excelReader.read(readSheet);
        excelReader.finish();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("OK");
        //设置请求的编码格式
        req.setCharacterEncoding("UTF-8");
        //获取普通表单项（获取参数）

        Part part = req.getPart("myfile");
        System.out.println(part);
        //通过Part对象得到上传的文件名
        String fileName = part.getSubmittedFileName();
        System.out.println("上传文件名：" + fileName);
        //得到文件存放的路径
        String filePath = req.getServletContext().getRealPath("/xlsx");
        File uploadFile = new File(filePath);
        // 如果此文件夹不存在就直接创建一个
        if (!uploadFile.exists()) {
            uploadFile.mkdir();
        }
        System.out.println("文件存放路径：" + filePath);
        //上传文件到指定目录
        part.write(filePath + "/" + fileName);
        String fi = filePath+"\\"+fileName;
        ExcelReader excelReader = EasyExcel.read(fi, Trainee.class, new DemoDataListener()).build();
        ReadSheet readSheet = EasyExcel.readSheet(0).build();
        excelReader.read(readSheet);
        excelReader.finish();
    }


}
